﻿Ext.define('passport.controller.FactoryController', {
    extend: 'Ext.app.Controller',

    stores: ['FactoryStore'],

    model: ['passport.model.FactoryModel'],

    views: ['factory.FactoryEditView', 'factory.FactoryListView'],

    refs: [
        {
            ref: 'factoriesPanel',
            selector: 'panel'
        }
    ],

    init: function() {

        this.control({
            'factoryEditView button[action=save]': {
                click: this.updateFactory
            },
						'factoryListView':{
							itemdblclick: this.editFactory
						},
						'factoryListView button[action=create]':{
							click: this.createFactory
						},
						'factoryListView button[action=delete]':{
							click: this.deleteFactory
						},
						'factoryListView button[action=refresh]':{
							click: this.refreshFactory
						}
						
						
        });
    },

    editFactory: function(grid, record) {
        var edit = Ext.create('passport.view.factory.FactoryEditView').show();
        edit.down('form').loadRecord(record);
    },

    updateFactory: function(button) {
        var win    = button.up('window'),
            form   = win.down('form'),
            record = form.getRecord(),
            values = form.getValues();

				if (form.getForm().isValid()){
	        record.set(values);
	        record.save({
	        		success: function() {
	        			this.getStore('FactoryStore').load();
	        			win.close();
	        			console.log("save object success!");	
	        		},
	        		failure : function() {
	        			console.log("failed to save the object");
	        		}
	        	});
	        
      	} else {
      		console.debug('Error occued while saving Factory');
      	}
    },
    
    createFactory: function(grid) {
    	var edit = Ext.create('passport.view.factory.FactoryEditView').show();
    	var record = Ext.create('passport.model.FactoryModel');
      edit.down('form').loadRecord(record);
    },
    
    deleteFactory: function(grid, record) {
    	console.log('delete');
    },
    
    refreshFactory: function() {
    	console.log("refresh");
    	//this.getFactoryStore().load({params:{page:1, start:0, limit:5, action:'save'}});
    }
});
